package com.caimiao.miao.library.utils.tip;

import com.caimiao.miao.library.utils.DateUtil;
import com.caimiao.miao.library.utils.storage.FileUtil;

public class PrintLog {
    private static final String DIR = ".Miao/.Log/";
    private static final String FILE = "Bluetooth_log_" + DateUtil.getTimestamp() + ".txt";
    private static final StringBuffer sb = new StringBuffer();
    private static boolean isStart = false;

    public static void printBle(String msg) {
        LogUtil.e("Bluetooth", msg);
        sb.append(DateUtil.getTimestamp()).append(": ").append(msg).append("\n");
        if (!isStart) {
            synchronized (PrintLog.class) {
                if (!isStart) {
                    startThread();
                }
            }
        }
    }

    public static void close() {
        isStart = false;
    }

    private static void startThread() {
        isStart = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isStart) {
                    String text = sb.toString();
                    int length = text.length();
                    sb.delete(0, length);
                    FileUtil.saveByAppend(text, DIR, FILE);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

}
